<?php

class PlayController extends BaseController
{
    private $req;

    public function init()
    {
        $this->req = $this->getRequest();
        if ($this->req->isXMLHttpRequest()) {
            Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
            $layout = Zend_Layout::getMvcInstance();
            if ($layout instanceof Zend_Layout) {
                $layout->disableLayout();
            }
        }
        $this->view->breadcrumb = array(array(
            'url' => '/play/showing',
            'name' => '竞猜管理',
        ));
    }

    /**
     * 场次类型
     */
    public function typeAction()
    {
        $play_type_biz = new \Biz\Play\Type();
        $size = Page::ValidatePageSize($this->req->get('pageSize'), '/play/type'); //每页显示条数
        $size = 100;
        $now = $this->req->get('p') ? $this->req->get('p') : 1;//当前页数
        $where = '';
        $list_result = $play_type_biz->getList($where, $now, $size);
        $page = new Page($list_result['total'], $size, $now, '/play/type?', 2);

        $this->view->size = $size;
        $this->view->now = $now;
        $this->view->pageStr = $page->showPage();
        $this->view->list_result = $list_result['lists'];
        $this->view->breadcrumb = array(
            array(
                'name' => '场次类别',
            )
        );
    }

    /**
     * 竞猜结果选项
     */
    public function settingAction()
    {
        $play_setting_biz = new \Biz\Play\Settings();
        $size = Page::ValidatePageSize($this->req->get('pageSize'), '/play/setting'); //每页显示条数
        $size = 100;
        $now = $this->req->get('p') ? $this->req->get('p') : 1;//当前页数
        $where = '';
        $list_result = $play_setting_biz->getList($where, $now, $size);
        $page = new Page($list_result['total'], $size, $now, '/play/setting?', 2);

        //保存数据到Redis
//        if($list_result['lists']){
//            $redisData = array();
//            foreach ($list_result['lists'] as $key => $item){
//                $redisData[$key]['id'] = $item['id'];
//                $redisData[$key]['type'] = $item['type'];
//                $redisData[$key]['title'] = $item['title'];
//                $redisData[$key]['score_a'] = $item['score_a'];
//                $redisData[$key]['score_b'] = $item['score_b'];
//            }
//            $redis_instance = \Util\Redis::getInstance();
//            $redis_instance->set('ziyan_setting_list',json_encode($redisData));
//        }

        $this->view->size = $size;
        $this->view->now = $now;
        $this->view->pageStr = $page->showPage();
        $this->view->list_result = $list_result['lists'];
        $this->view->breadcrumb = array(
            array(
                'name' => '竞猜选项',
            )
        );
    }

    public function settingAddAction()
    {
        if($this->req->isPost()){
            $insertData = array();
            $insertData['type'] = $this->req->getPost('type');
            $insertData['title'] = $this->req->getPost('title');
            $insertData['score_a'] = $this->req->getPost('score_a');
            $insertData['score_b'] = $this->req->getPost('score_b');

            $Setting_insert = \Biz\Play\Settings::insert($insertData);
            if($Setting_insert['isok']){
                return Response::Success('','添加成功！');
            }else{
                return Response::Error(0, ' 添加失败！'.$Setting_insert['msg']);
            }
        }

        $typeArr = \Biz\Play\Settings::TYPE_ARR;
        $this->view->typeArr = $typeArr;
        $this->view->breadcrumb = array(
            array(
                'name' => '新增选项',
            )
        );
    }

    /**
     * 赛程安排
     */
    public function showingAction()
    {
        //比赛队伍
        $player_biz = new \Biz\Player();
        $player_list = $player_biz->getPlayerList('', 1, 100);

        $showing_biz = new \Biz\Play\Showings();
        $size = Page::ValidatePageSize($this->req->get('pageSize'), '/play/showing'); //每页显示条数
        $size = 100;
        $now = $this->req->get('p') ? $this->req->get('p') : 1;//当前页数
        $where = '';
        $list_result = $showing_biz->getList($where, $now, $size);
        $page = new Page($list_result['total'], $size, $now, '/play/showing?', 2);

        //保存数据到Redis
//        if($list_result['lists']){
//            $redisData = array();
//            foreach ($list_result['lists'] as $key => $item){
//                $redisData[$key]['id'] = $item['id'];
//                $redisData[$key]['type'] = $item['type'];
//                $redisData[$key]['player_a'] = $item['player_a'];
//                $redisData[$key]['player_b'] = $item['player_b'];
//                $redisData[$key]['start_time'] = $item['start_time'];
//                $redisData[$key]['play_number'] = $item['play_number'];
//                $redisData[$key]['open_time'] = $item['open_time'];
//                $redisData[$key]['stop_time'] = $item['stop_time'];
//                $redisData[$key]['score_a'] = $item['score_a'];
//                $redisData[$key]['score_b'] = $item['score_b'];
//                $redisData[$key]['status'] = $item['status'];
//                $redisData[$key]['week_own'] = $item['week_own'];
//            }
//            $redis_instance = \Util\Redis::getInstance();
//            $redis_instance->set('ziyan_showing_list',json_encode($redisData));
//        }

        $this->view->size = $size;
        $this->view->now = $now;
        $this->view->pageStr = $page->showPage();
        $this->view->list_result = $list_result['lists'];
        $this->view->player_list = $player_list['lists'];
        $this->view->breadcrumb = array(
            array(
            'name' => '赛程安排',
        ));
    }

    public function showingAddAction()
    {
        if($this->req->isPost()){
            $insertData = array();
            $insertData['type'] = $this->req->getPost('type');
            $insertData['player_a'] = $this->req->getPost('player_a');
            $insertData['player_b'] = $this->req->getPost('player_b');
            $insertData['play_number'] = $this->req->getPost('play_number');
            $insertData['start_time'] = $this->req->getPost('start_time');
            $insertData['open_time'] = $this->req->getPost('open_time');
            $insertData['stop_time'] = $this->req->getPost('stop_time');
            $insertData['score_a'] = $this->req->getPost('score_a');
            $insertData['score_b'] = $this->req->getPost('score_b');
            $insertData['status'] = \Biz\Play\Showings::STATUS_WAIT;

            $_insert = \Biz\Play\Showings::insert($insertData);
            if($_insert['isok']){
                return Response::Success('','添加成功！');
            }else{
                return Response::Error(0, ' 添加失败！'.$_insert['msg']);
            }
        }

        $typeArr = \Biz\Play\Showings::TYPE_ARR;

        //比赛队伍
        $player_biz = new \Biz\Player();
        $list_result = $player_biz->getPlayerList('', 1, 100);

        $this->view->typeArr = $typeArr;
        $this->view->playerArr = $list_result['lists'];
        $this->view->breadcrumb = array(
            array(
                'name' => '新增赛程',
            )
        );
    }

    public function showingEditAction()
    {
        //获得赛程信息
        $id = $this->req->get('id');
        $thisInfo = \Biz\Play\Showings::getInfo($id);

        if($this->req->isPost()){
            $thisInfo['open_time'] = $this->req->getPost('open_time');
            $thisInfo['stop_time'] = $this->req->getPost('stop_time');
            $thisInfo['score_a'] = $this->req->getPost('score_a');
            $thisInfo['score_b'] = $this->req->getPost('score_b');

            $is_update = \Biz\Play\Showings::update($thisInfo);
            if($is_update['isok']){
                return Response::Success('','更新成功！');
            }else{
                return Response::Error(0, '更新失败！'.$is_update['msg']);
            }
        }

        //小组类别
        $typeArr = \Biz\Play\Showings::TYPE_ARR;

        //比赛队伍
        $player_biz = new \Biz\Player();
        $list_result = $player_biz->getPlayerList('', 1, 100);

        $this->view->thisInfo = $thisInfo;
        $this->view->typeArr = $typeArr;
        $this->view->playerArr = $list_result['lists'];

        $this->view->breadcrumb = array(
            array(
                'name' => '更新赛程',
            )
        );
    }

    public function showingFinalAction()
    {
        $type = $this->req->getPost('type');
        switch ($type){
            case 'show':
                $id = $this->req->getPost('id');
                $thisInfo = \Biz\Play\Showings::getInfo($id);
                $this->view->thisInfo = $thisInfo;

                //比赛队伍
                $player_biz = new \Biz\Player();
                $list_result = $player_biz->getPlayerList('', 1, 100);
                $this->view->player_list = $list_result['lists'];

                $typeArr = \Biz\Play\Settings::TYPE_ARR;

                $play_setting_biz = new \Biz\Play\Settings();
                $setting_list = $play_setting_biz->getList('', 1, 100);

                $playTypeArr = array();
                foreach ($typeArr as $key => $val){
                    $playTypeArr[$key]['name'] = $val;
                    foreach ($setting_list['lists'] as $item){
                        if($item['type'] == $key){
                            $playTypeArr[$key]['child'][] = $item;
                        }
                    }
                }
                $this->view->setting_list = $playTypeArr;

                $result['htmlcode'] = $this->view->render('play/showing-final.phtml');
                return Response::Success($result,'');
                break;
            case 'submit':
                $id = $this->req->getPost('id');
                $score_a = $this->req->getPost('score_a');
                $score_b = $this->req->getPost('score_b');
                $play_result = $this->req->getPost('play_result');

                $baseOrm = new \Base\BaseOrmModel();
                $baseOrm->beginTransaction();
                try{

                    $_orm = \Biz\Play\Showings::getInfo($id);
                    $time_finish = strtotime($_orm['start_time']) + (90 * 60);
                    $thisTime = time();
                    if($thisTime < $time_finish){
                        throw new \Exception('比赛尚未结束，比赛开始90分钟后视为比赛结束！');
                    }
                    //处理基本数据
                    $_orm['score_a'] = $score_a;
                    $_orm['score_b'] = $score_b;
                    $_orm['status'] = \Biz\Play\Showings::STATUS_FINISH;
                    $is_update = \Biz\Play\Showings::update($_orm);
                    if(!$is_update['isok']){
                        throw new \Exception($is_update['msg']);
                    }

                    //插入结果数据
                    foreach ($play_result as $key => $val){
                        $insertResult = array(
                            'play_type' => $key,
                            'play_showing_id' => $id,
                            'result_setting_id' => $val
                        );
                        $is_insert = \Biz\Play\Result::insert($insertResult);
                        if(!$is_insert['isok']){
                            throw new \Exception($is_insert['msg']);
                        }
                    }

                    //处理竞猜记录是否中奖
                    //计算积分，生成积分日志
                    //处理周排行
                    $where = 'play_show_id = '.$id;
                    $play_active_total = \Biz\Play\Active::getTotal($where);
                    $size = 1000;
                    $pages = ceil($play_active_total/$size);
                    for ($i = 1; $i <= $pages; $i++){
                        $activeList = \Biz\Play\Active::getList($where,$i,$size);
                        if($activeList['lists']){
                            foreach ($activeList['lists'] as $value){
                                $uid = 0;
                                if(in_array($value['play_target_id'],$play_result)){
                                    $value['status'] = \Biz\Play\Active::STATUS_YES;
                                    $uid = $value['uid'];
                                }else{
                                    $value['status'] = \Biz\Play\Active::STATUS_NO;
                                }
                                $update_active = \Biz\Play\Active::update($value);
                                if(!$update_active['isok']){
                                    throw new Exception($update_active['msg']);
                                }
                                //获得积分
                                if($uid){

                                    //用户数据有误，跳过
                                    try{
                                        $userAccount = \Biz\User::getAccount($uid);
                                    }catch (\Exception $e){
                                        continue;
                                    }

                                    $score = 0;
                                    switch ($value['play_type']){
                                        case \Biz\Play\Settings::TYPE_A:
                                            $score = \Util\Config::get('ziyan_score_a');
                                            break;
                                        case \Biz\Play\Settings::TYPE_B:
                                            $score = \Util\Config::get('ziyan_score_b');
                                            break;
                                        case \Biz\Play\Settings::TYPE_C:
                                            $score = \Util\Config::get('ziyan_score_c');
                                            break;
                                    }
                                    $userAccount['score'] = $userAccount['score'] + $score;

                                    //周排行数据
                                    if($_orm['week_own']){
                                        switch ($_orm['week_own']){
                                            case 1:
                                                $userAccount['one_week_score'] = $userAccount['one_week_score'] + $score;
                                                break;
                                            case 2:
                                                $userAccount['two_week_score'] = $userAccount['two_week_score'] + $score;
                                                break;
                                            case 3:
                                                $userAccount['three_week_score'] = $userAccount['three_week_score'] + $score;
                                                break;
                                            case 4:
                                                $userAccount['four_week_score'] = $userAccount['four_week_score'] + $score;
                                                break;
                                            default:
                                                break;
                                        }
                                    }

                                    //更新账户信息
                                    $account_update = \Biz\User::updateAccount($userAccount);
                                    if($account_update){
                                        //添加积分日志
                                        $insertData = array(
                                            'uid' => $uid,
                                            'score' => $score,
                                            'play_show_id' => $_orm['id'],
                                            'play_target_id' => $value['play_target_id'],
                                            'paly_type' => $value['play_type'],
                                            'target_title' => ''
                                        );
                                        $log_insert = \Biz\User::insertScoreLog($insertData);
                                        if(!$log_insert){
                                            throw new \Exception('积分日志记录失败');
                                        }
                                    }else{
                                        throw new \Exception('账户积分更新失败');
                                    }
                                }
                            }
                        }
                    }

                    $baseOrm->commit();
                }catch (\Exception $e){
                    $baseOrm->rollBack();
                    return Response::Error('201',$e->getMessage());
                }
                return Response::Success('','操作成功');
                break;
            default:
                return Response::Error('201','非法请求');
                break;
        }
        return Response::Error('201','非法请求');
    }

    public function activeAction()
    {
        $active_biz = new \Biz\Play\Active();
        $size = Page::ValidatePageSize($this->req->get('pageSize'), '/play/active'); //每页显示条数
        $now = $this->req->get('p') ? $this->req->get('p') : 1;//当前页数
        $where = '';
        $list_result = $active_biz->getListWithInfo($where, $now, $size);
        $page = new Page($list_result['total'], $size, $now, '/play/active?', 2);

        $this->view->size = $size;
        $this->view->now = $now;
        $this->view->pageStr = $page->showPage();
        $this->view->list_result = $list_result['lists'];
        $this->view->breadcrumb = array(
            array(
                'name' => '竞猜记录',
            ));
    }
}